'use client'

import { useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'

export default function TestApiDataPage() {
  const [apiData, setApiData] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const testApi = async () => {
    setLoading(true)
    setError(null)
    
    try {
      console.log('开始调用API...')
      const response = await fetch('/api/field-metadata?tableName=table_c2')
      console.log('API响应状态:', response.status)
      
      const data = await response.json()
      console.log('API响应数据:', data)
      
      setApiData(data)
    } catch (err) {
      console.error('API调用失败:', err)
      setError(err instanceof Error ? err.message : 'API调用失败')
    } finally {
      setLoading(false)
    }
  }

  const getDataSourceColor = (source: string) => {
    const colors: Record<string, string> = {
      'P': 'bg-blue-100 text-blue-800',
      'E': 'bg-green-100 text-green-800',
      'M': 'bg-orange-100 text-orange-800',
      'O': 'bg-purple-100 text-purple-800',
      'C': 'bg-yellow-100 text-yellow-800',
      'R': 'bg-red-100 text-red-800'
    }
    return colors[source] || 'bg-gray-100 text-gray-800'
  }

  return (
    <div className="p-8 space-y-6">
      <h1 className="text-2xl font-bold">API数据测试</h1>
      
      <Card>
        <CardHeader>
          <CardTitle>API测试控制</CardTitle>
        </CardHeader>
        <CardContent>
          <Button onClick={testApi} disabled={loading}>
            {loading ? '加载中...' : '测试 /api/field-metadata?tableName=table_c2'}
          </Button>
          
          {error && (
            <div className="mt-4 p-4 bg-red-100 border border-red-300 rounded text-red-700">
              错误: {error}
            </div>
          )}
        </CardContent>
      </Card>

      {apiData && (
        <>
          {/* API响应概览 */}
          <Card>
            <CardHeader>
              <CardTitle>API响应概览</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <div className="text-sm font-medium text-gray-600">成功状态</div>
                  <div className="text-lg font-semibold">
                    {apiData.success ? '✅ 成功' : '❌ 失败'}
                  </div>
                </div>
                <div>
                  <div className="text-sm font-medium text-gray-600">字段数量</div>
                  <div className="text-lg font-semibold">
                    {apiData.data?.fieldCount || 0}
                  </div>
                </div>
                <div>
                  <div className="text-sm font-medium text-gray-600">表名</div>
                  <div className="text-lg font-semibold">
                    {apiData.data?.tableMetadata?.table_name || 'N/A'}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* 字段按数据来源分组 */}
          {apiData.data?.fields && (
            <Card>
              <CardHeader>
                <CardTitle>字段按数据来源分组</CardTitle>
              </CardHeader>
              <CardContent>
                {(() => {
                  const fieldsBySource = apiData.data.fields.reduce((acc: any, field: any) => {
                    if (!acc[field.data_source]) acc[field.data_source] = []
                    acc[field.data_source].push(field)
                    return acc
                  }, {})
                  
                  const sources = Object.keys(fieldsBySource).sort()
                  
                  return (
                    <div className="space-y-4">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        {sources.map(source => (
                          <div key={source} className="text-center p-4 border rounded">
                            <Badge className={getDataSourceColor(source)}>
                              {source}
                            </Badge>
                            <div className="mt-2 text-lg font-semibold">
                              {fieldsBySource[source].length}
                            </div>
                            <div className="text-xs text-gray-500">个字段</div>
                          </div>
                        ))}
                      </div>
                      
                      <div className="space-y-4">
                        {sources.map(source => (
                          <div key={source}>
                            <h4 className="font-medium mb-2 flex items-center space-x-2">
                              <Badge className={getDataSourceColor(source)}>
                                {source}
                              </Badge>
                              <span>数据来源字段列表</span>
                            </h4>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-2 ml-4">
                              {fieldsBySource[source].map((field: any) => (
                                <div key={field.id} className="text-sm border rounded p-2">
                                  <div className="font-medium">{field.field_name}</div>
                                  <div className="text-gray-600 text-xs">
                                    ID: {field.id} | 类型: {field.data_type} | 必填: {field.is_required ? '是' : '否'}
                                  </div>
                                </div>
                              ))}
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )
                })()}
              </CardContent>
            </Card>
          )}

          {/* 原始JSON数据 */}
          <Card>
            <CardHeader>
              <CardTitle>原始API响应</CardTitle>
            </CardHeader>
            <CardContent>
              <pre className="text-xs bg-gray-100 p-4 rounded overflow-auto max-h-96">
                {JSON.stringify(apiData, null, 2)}
              </pre>
            </CardContent>
          </Card>
        </>
      )}
    </div>
  )
}
